package com.tiger.service;


import com.tiger.exception.ServiceException;
import com.tiger.mapper.BookDao;
import com.tiger.pojo.JsonResult;
import com.tiger.pojo.book.Book;
import com.tiger.utils.Regex;
import com.tiger.utils.TimeCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Service
public class BookServiceImpl implements BookService {
	@Autowired
	BookDao bookDao;
	/**
	 * 保存预约信息
	 */
	@Override
	public JsonResult doSave(Book book) {
		// 1.校验参数
		String userName = book.getUserName();
		String tel = book.getTel();
		Date bookTime = book.getBookTime();
		String manager = book.getManager();
		String managerTel = book.getManagerTel();
		if(userName==null||tel==null||bookTime==null||manager==null||managerTel==null) {
			throw new IllegalArgumentException("输入框不能为空");
		}
		if(userName.equals(" ")||tel.equals(" ")||manager.equals(" ")||managerTel.equals(" ")) {
			throw new IllegalArgumentException("输入框不能为空格");
		}
		//校验手机号码
		Regex.telRegex(tel);
		Regex.telRegex(managerTel);
		//校验时间
		TimeCheck.hourCheck(book.getBookTime());
		//保存信息
		int row=bookDao.doSave(book);
		//希望时间到了(endTime)自动修改活动状态
				//解决方案:基于任务调度去实现(任务调度-基于时间的设计自动执行任务)
				//代码方案:
				//1)借助Java中的Timer对象去实现
				Timer timer=new Timer();//此对象创建时会在底层启动一个线程,通过此线程对时间进行监控
				//2)执行任务(任务类型为TimerTask类型)
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						//在此位置修改活动的状态信息
						
						bookDao.updateState(book.getId());
						timer.cancel();
					}
				}, book.getBookTime());
				//2)借助Java线程池中的任务调度对象(ScheduledExecutorService )去实现
				//3)借助第三方框架去实现(quartz)
		//返回结果
		return new JsonResult(row);
	}
	
	@Override
	/**
	 * 查找预约界面
	 */
	public List<Book> FindBook(String userName) {
		// TODO Auto-generated method stub
		if(userName==null||userName.equals("")) {
			throw new IllegalArgumentException("网络出现问题，请刷新重试");
		}
		List<Book> list=bookDao.findBook(userName);
		if(list==null||list.size()<0) {
			throw new ServiceException("您暂时没有预约信息");
		}
		
		return list;
	}
	
	//进行删除预约
	@Override
	public int doDeleteObjectsByIds(Integer[] ids) {
		// TODO Auto-generated method stub
		
		if(ids==null||ids.length<0) {
			throw new IllegalArgumentException("没有选中信息");
		}
		
		int rows=bookDao.doDeleteObjectsByIds( ids) ;
		if(rows==0) {
			throw new ServiceException("记录已经不存在");
		}
		return rows;
	}

	@Override
	public int doUpdateObject(Book book) {
		// TODO Auto-generated method stub
		//1,参数校验
		if(book.getId()==null||book.getId()==0) {
			throw new IllegalArgumentException("没有选中信息，请刷新一下");
		}
		if(book.getBookTime()==null) {
			throw new IllegalArgumentException("请填写日期信息");
		}
		
		Regex.telRegex(book.getTel());
		TimeCheck.hourCheck(book.getBookTime());
		//进行操作
		int row=bookDao.doUpdateObject(book);
		return row;
	}

}
